<?php
/**
 * Created by JetBrains PhpStorm.
 * User: tcore
 * Date: 21.01.12
 * Time: 18:45
 * To change this template use File | Settings | File Templates.
 */
class jsLangCommand extends CConsoleCommand
{
	public function run($args)
	{
		$messagesPath = Yii::app()->basePath . DIRECTORY_SEPARATOR . 'messages' . DIRECTORY_SEPARATOR;
		if(!is_dir($messagesPath))
		{
			echo "[e] $messagesPath is not dir\n";
			exit;
		}
		$messagesDir = opendir($messagesPath);
		while (false !== ($dir = readdir($messagesDir)))
		{
			if (is_dir($messagesPath . $dir) && $dir !== '.' && $dir !== '..')
			{
				$subPath = $messagesPath . $dir . DIRECTORY_SEPARATOR;
				$this->getLangFiles($subPath, $dir);
			}
		}
	}

	private function getLangFiles($path, $lang)
	{
		$dir = opendir($path);
		while (false != ($file = readdir($dir)))
		{
			$filePath = $path . $file;
			if(is_file($filePath))
			{
				$this->generateJsLang($filePath, $lang, substr($file, 0, -4));
			}
		}
	}

	private function generateJsLang($filePath, $lang, $category)
	{
		$jsMessagesPath = Yii::app()->basePath . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'assets' .
			DIRECTORY_SEPARATOR . 'messages' . DIRECTORY_SEPARATOR;
		if(!is_dir($jsMessagesPath))
		{
			echo "[e] $jsMessagesPath doesn't exist\n";
			exit;
		}
		$langPath = $jsMessagesPath . $lang . DIRECTORY_SEPARATOR;
		if(!is_dir($langPath))
		{
			mkdir($langPath, 0777);
		}
		$jsMessagesFile = $langPath . $category . '.js';
		if(is_file($jsMessagesFile))
		{
			unlink($jsMessagesFile);
		}
		$jsMessagesFileHandler = fopen($jsMessagesFile, 'w');
		$messages = '$(document).ready(function(){'.AHelper::arrayToJSObject(require($filePath), 'window.t["'.$category.'"]').'});';
		fputs($jsMessagesFileHandler, $messages, strlen($messages));
		fclose($jsMessagesFileHandler);
		echo "[i] $jsMessagesFile created successfully!\n";
	}
}
